package com.yanqu.road.server.logic.thread;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eALiActivityChannel;
import com.yanqu.road.entity.enums.eALiPayTaskType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.task.UserTaskData;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.logic.task.BaseCondition;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.SortedMap;
import java.util.TreeMap;

public class ALiPayTask extends GeneralTask {
    private Logger logger = LogManager.getLogger(ALiPayTask.class.getName());

    private GamePlayer player;
    private String appExt;
    private BaseCondition baseCondition;
    private UserTaskData task;

    public ALiPayTask(GamePlayer player, String appExt, BaseCondition baseCondition, UserTaskData task) {
        super();

        this.player = player;
        this.appExt = appExt;
        this.baseCondition = baseCondition;
        this.task = task;
    }

    @Override
    public void doRun() {
        if(!"37zfbxyx".equals(player.getAppId())) {
            return;
        }
        int paramsOne = 0;
        if(baseCondition.getTaskConditionInfo().getParamList().size() > 0) {
            paramsOne = baseCondition.getTaskConditionInfo().getParamList().get(0).intValue();
        }
        String actionCode;
        if(baseCondition.getTaskConditionInfo().getType() == eGamePlayerEventType.BanquetJoinTimes.getValue()){
               actionCode = "jwdzg_game_fuyan_5";
        }else {
            eALiPayTaskType taskType = com.yanqu.road.entity.enums.eALiPayTaskType.geteALiPayTaskTypeByType(baseCondition.getTaskConditionInfo().getType());
            if (taskType == null) {
                return;
            }
            if (!taskType.isExtend()) {
                actionCode = taskType.getTaskSign();
            } else {
                actionCode = eALiActivityChannel.getALiActivityChannelCode(paramsOne);
            }
            if (StringUtils.isNullOrEmpty(actionCode)) {
                logger.info("ALiPayTask userId:{},actionCode:{}", player.getUserId(), actionCode);
                return;
            }
        }
        SortedMap<String, String> paramMap = new TreeMap<>();
        paramMap.put("appid", player.getAppId());
        paramMap.put("game_id", ChannelConfig.ALIPAY_GAME_ID);
        paramMap.put("uid", player.getUserInfo().getPlatformUserId());
        paramMap.put("action_code", actionCode);
        paramMap.put("action_finish_date", String.valueOf(System.currentTimeMillis() / 1000));
        // todo 这个字段是获取支付宝小程序channel，服务端暂无，约定先传other
        paramMap.put("action_finish_channel", "other");
        paramMap.put("app_ext", appExt);
        // 37计算规则里需要一个 & 链接签名
        String sign = SignHelper.getSign(paramMap, "&" + ChannelConfig.ALIPAY_REPORT_SIGN_KEY);
        paramMap.put("sign", sign);
        try {
            String url = ChannelConfig.ALIPAY_REPORT_URL;
            // 空的就不发
            if(StringUtils.isNullOrEmpty(url)) {
                return;
            }
//            logger.info("ALiPayTask url:{}", url);
            synchronized (task) {
                if (task.getState() == 0) {
                    String result = HttpHelper.doPost(url, paramMap, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject.containsKey("code") && jsonObject.getIntValue("code") == 1) {
                        changeState();
                    }
                    logger.info("ALiPayTask userId:{},actionCode:{},code:{},msg:{}", player.getUserId(), actionCode,
                            jsonObject.getIntValue("code"), jsonObject.getString("msg"));
                }
            }
        } catch (Exception e) {
            logger.error("ALiPayTask userId:{},actionCode:{},error:", player.getUserId(), actionCode, e);
        }
    }

    // 设置条件状态移除条件设置
    private void changeState(){
        task.setState(1);
        task.setFinishTime(System.currentTimeMillis() / 1000);
        if (null != baseCondition) {
            baseCondition.removeTrigger(player);
        }
    }
}
